from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required

from s_te.utils import delete_slug
from bl_g.models import Entry
from bl_g.admin.forms import EntryForm


@staff_member_required
def main(request, template_name="bl_g/admin/main.html"):
    """
    The main page of the admin, listing all entries
    """
    entries = Entry.objects.all()
    return render_to_response(template_name, {'entries':entries, 'nav_page': 'bl_g_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="bl_g/admin/create.html"):
    """
    Create a new entry
    """
    if request.POST:
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Blog entry created.")
            return HttpResponseRedirect(reverse('bl_g_admin_main'))
    else:
        form = EntryForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="bl_g/admin/edit.html"):
    """
    Edit an existing entry
    """
    entry = get_object_or_404(Entry, slug=slug)
    if request.POST:
        form = EntryForm(request.POST, instance=entry)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="Blog entry saved.")
            return HttpResponseRedirect(reverse('bl_g_admin_main'))
    else:
        form = EntryForm(instance=entry)
    return render_to_response(template_name, {'entry':entry, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing entry
    """
    delete_slug(Entry, request)
    request.user.message_set.create(message="Blog entry deleted.")
    return HttpResponseRedirect(reverse('bl_g_admin_main'))
